/**
 * @file page_sound.cpp
 * @author Forairaaaaa
 * @brief
 * @version 0.1
 * @date 2023-11-18
 *
 * @copyright Copyright (c) 2023
 *
 */
#include "../app_settings.h"
#include "../../utils/system/ui/ui.h"
#include "../../../hal/hal.h"
#include <WiFi.h>

using namespace MOONCAKE::APPS;
using namespace SYSTEM::UI;

void AppSettings::_page_wifi()
{
    while (1)
    {
        HAL::DisplayPageString(20, 100, "Wifi Searching...");

        std::vector<std::string> items = {"[WIFI CONFIG]"};
        String Saved_str = ">Saved: " + String(HAL::GetSystemConfig().wifi_ssid);
        items.push_back(Saved_str.c_str());

        // search wifi ssid
        int numberOfNetworks = WiFi.scanNetworks();
        spdlog::info("numberOfNetworks: {}", numberOfNetworks);
        for (int i = 0; i < numberOfNetworks; i++)
        {
            String str = "SSID: " + WiFi.SSID(i) + "Strength: " + WiFi.RSSI(i);
            spdlog::info(str.c_str());
            items.push_back(WiFi.SSID(i).c_str());
        }
        items.push_back("Back");

        auto selected = _data.select_menu->waitResult(items);
        spdlog::info("selected: {}", selected);

        if (selected == numberOfNetworks + 1 || selected == -2)
        {
            spdlog::info("break ");
            break;
        }
        else if (selected == 1)
        {
            spdlog::info("choose saved ");
        }
        else
        {
            strcpy(HAL::GetSystemConfig().wifi_ssid, WiFi.SSID(selected - 2).c_str());
            HAL::SaveSystemConfig();

            String str = "Save: " + WiFi.SSID(selected - 2);
            HAL::DisplayPageString(5, 100, str.c_str());
            HAL::Delay(2000);
            break;
        }
    }
}
